package com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lqjava.tuxiaowang.tuxiaowang.beans.entity.response.MiniProgramLoginResponse;
import com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.wechat.props.WchatProps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class WechatMPSDK {
	
	@Autowired
	WchatProps props;

	@Autowired
    WechatSDK wechatSDK;
	
	@Autowired
	RestTemplate wxRestTemplate;
	
	@Autowired
	MiniProgramInfoService miniProgramInfoService;
	
	
	public MiniProgramLoginResponse login(MiniProgramLoginRequest request) {
		MiniProgramInfo info = miniProgramInfoService.get(MiniProgramTypeEnum.WECHAT.getCode(),request.getAppid());
		if(info == null){
			ServiceException.throwBusiness("当前appid没有有效的微信小程序");
		}
		
		String fmt = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
		String url = String.format(fmt, info.getAppid(),info.getAppsecret(),request.getCode());
		ResponseEntity<String> forEntity = wxRestTemplate.getForEntity(url, String.class);
		
		JSONObject parseObject = JSON.parseObject(forEntity.getBody());
		String sk = parseObject.getString("session_key");
		String openid = parseObject.getString("openid");
		if(sk == null || openid == null){
			System.out.println(parseObject);
			ServiceException.throwBusiness("微信小程序获取openid失败");
		}
		
		OTherUserResponse oTherUserResponse = new OTherUserResponse();
		oTherUserResponse.setNickName(openid);
		oTherUserResponse.setGender("未知");
		oTherUserResponse.setOpenid(openid);
		oTherUserResponse.setUserType(UserTypeEnums.WECHART.getCode());
		oTherUserResponse.setSk(sk);
		oTherUserResponse.setPhone(openid);
		
		String loginSK = UUIDUtil.getUUID();
		MiniProgramLoginResponse response = new MiniProgramLoginResponse();
		response.setOpenid(openid);
		response.setSk(loginSK);
		wechatSDK.login(oTherUserResponse, loginSK);
		return response;
	}
	

	
}
